package com.ysh.xiaomi.dao.impl;

import com.ysh.xiaomi.dao.UserDao;
import com.ysh.xiaomi.pojo.TbAddress;
import com.ysh.xiaomi.pojo.TbUser;
import com.ysh.xiaomi.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.Date;

/**
 * 袁胜虎 on 2022/8/15 22:44
 */
public class UserDaoImpl implements UserDao {
    @Override
    public int AddUser(TbUser tbUser) {
        try {
            QueryRunner qr = new QueryRunner();
            String sql ="INSERT INTO tb_user(username,password,email,gender,code)VALUES(?,?,?,?,?)";
            int count = qr.update(DbUtils.getConn(), sql,tbUser.getUsername(),tbUser.getPassword(),tbUser.getEmail(),tbUser.getGender(),tbUser.getCode());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int AddAddress(TbAddress address) {
        try {
            QueryRunner qr = new QueryRunner();
            String sql ="INSERT INTO tb_address(detail,name,phone)VALUES(?,?,?)";
            int count = qr.update(DbUtils.getConn(), sql,address.getDetail(),address.getName(),address.getPhone());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public TbUser findByUser(String name) {
        try {
            QueryRunner qr = new QueryRunner();
            String sql = "select * from tb_user where username = ?";
            TbUser user = qr.query(DbUtils.getConn(), sql, new BeanHandler<>(TbUser.class), name);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateLoginTime(Long userId) {
        QueryRunner qr = new QueryRunner();
        //跟新登录时间
        String sql = "update tb_user set  lastlogintime=currentlogintime,currentlogintime = ? where id =?";
        try {
            int count = qr.update(DbUtils.getConn(), sql, new Date(), userId);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public TbUser selectByUsername(String username) {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from tb_user where username= '"+username+"' ";
        try {
            qr.query(DbUtils.getConn(),sql,new BeanHandler<>(TbUser.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
